package client.global.commlib.base

import android.content.Context
import android.view.LayoutInflater
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView

abstract class BaseAdapter<T> :
    RecyclerView.Adapter<RecyclerView.ViewHolder> {
    protected val layoutInflater: LayoutInflater by lazy {
        LayoutInflater.from(context)
    }

    val mItems: MutableList<T?> by lazy {
        ArrayList<T?>()
    }

    override fun getItemCount(): Int {
        return mItems.size
    }

    constructor(context: Context) : this(context, object : DiffUtil.ItemCallback<T>() {
        override fun areItemsTheSame(oldItem: T, newItem: T): Boolean {
            return false
        }

        override fun areContentsTheSame(oldItem: T, newItem: T): Boolean {
            return false
        }
    })

    constructor(context: Context, diffCallback: DiffUtil.ItemCallback<T>) : super() {
        this.context = context
    }


    protected val context: Context

    fun getItems(): List<T?> {
        return mItems
    }

    fun removeItem(item: T) {
        val index = mItems.indexOf(item)
        if (index >= 0) {
            mItems.removeAt(index)
            notifyItemRemoved(index)
        }
    }

    fun removeItem(index: Int) {
        if (index >= 0 && index < itemCount) {
            mItems.removeAt(index)
            notifyItemRemoved(index)
        }
    }

    fun removeItemByIndex(index: Int) {
        if (index >= 0 && index < itemCount) {
            mItems.removeAt(index)
            notifyItemRemoved(index)
        }
    }

    open fun submitList(list: List<T?>?) {
        mItems.clear()
        list?.let {
            mItems.addAll(list)
        }
        notifyDataSetChanged()
    }

    fun getItem(position: Int): T {
        return mItems.get(position)!!
    }

    fun appendItems(items: List<T?>?) {
        if (items != null && items.size > 0) {
            val size = itemCount
            mItems.addAll(items)
            notifyItemRangeInserted(size, items.size)
        }
    }


}